#!/bin/sh

#echo "传递参数："
#echo "执行的文件名：$0"
#echo "第一个参数为：$1"
#echo "第二个参数为：$2"

#dirname $0，取得当前执行的脚本文件的父目录
#cd `dirname $0`，进入这个目录(切换当前工作目录)
#pwd，显示当前工作目录(cd执行后的)
#echo "scriptPath1: "$(cd `dirname $0`; pwd)
#echo "scriptPath2: "$(dirname $(readlink -f $0))


#重启tomcat函数
function restart(){
	echo "restart ..."
	#$1 服务名称
	#$2 tomcat所在父目录，没传取脚本所在目录
	basePath="";
	if [ "$2" ]; then
	    basePath=$2;
	else
	    basePath=$(cd `dirname $0`; pwd);
	fi
	
	#查询目录下对应的tomcat服务文件名
	tomcatDirName=""
	tomcatRunFile=""
	for file in $(ls $basePath)
	do
	    if test -d $file
	    then
		#echo "fileName:"$file
		#echo "name"$(basename $file)
		#目录名包含服务名，则认为找到服务名对应的服务tomcat所在目录
		# 例如： tomcat_ktrade_8015 包含 _ktrade_
		if [[ $file =~ "_${1}_" ]]; then
		    tomcatDirName=$file
		    tomcatRunFile="${basePath}/${file}/bin/startup.sh"
		fi;
	    fi

	done
	if [ "$tomcatDirName" ]; then
	    #echo "tomcatDirName:"$tomcatDirName
	    echo ""
	else
	    echo "Did not find the tomcat [${1}] service folder"
	    return 1;
	fi
	if [ "$tomcatRunFile" ]; then
	    echo "tomcatRunFile:"$tomcatRunFile
	else
	    echo "Did not find the tomcat [${1}] service run file"
	    return 2;
	fi

	PID=$(ps -ef|grep ${tomcatDirName}|grep -v grep|awk '{print $2}');

	if [ -z "$PID" ]; then
	    KILL_SLEEP=-1;
	    echo "Could not find the tomcat( ${tomcatDirName} ) process."
	else
	    echo "Kill the tomcat( ${tomcatDirName} ) process id ${PID}."
	    KILL_SLEEP=30;
	    kill -9 $PID
	fi

	# 杀掉进程，最大循环等待30秒 
	while [ $KILL_SLEEP -ge 0 ]; do
	    kill -0 $PID >/dev/null 2>&1
	    if [ $? -gt 0 ]; then
		# 大于0，说明没找到进程，则进程已经被杀了
		KILL_SLEEP_INTERVAL=0
		echo "The Tomcat process has been killed.The process id is ${PID}."
		break
	    fi
	    if [ $KILL_SLEEP -gt 0 ]; then
		sleep 1
		echo "Please wait for process id ${PID}, it has passed  $(expr 31 - $KILL_SLEEP) seconds."
	    fi
	    if [ $KILL_SLEEP -eq 0 ]; then
		echo "Tomcat did not stop in time. To aid diagnostics a thread dump has been written to standard out.The process id is ${PID}."
		kill -3 $PID
	    fi
	    KILL_SLEEP=`expr $KILL_SLEEP - 1 `
	done

	# 启动服务
	nohup $tomcatRunFile >/dev/null 2>&1 &
	# 出现异常时， 去掉 >/dev/null ，将异常输出到控制台，方便查错
	#nohup $tomcatRunFile 2>&1 &

	NEWPID=$(ps -ef|grep ${tomcatDirName}|grep -v grep|awk '{print $2}');
	if [ -z "$NEWPID" ]; then
	    echo "Tomcat( ${tomcatDirName} ) can't run.";
	    #exit 1
	else
	    echo "Tomcat( ${tomcatDirName} ) is running with PID ${NEWPID}.";
	    #exit 0
	fi

	echo "End restart ..."
   return 0;
}

#目前支持的服务名，新的需要这里添加
serverNames=("dubble" "admin" )
#指定运行目录
basePath="/home/ygjrzc";

function showWarn(){
    #echo "test restart exception"
    showName="";
    for serverName in ${serverNames[@]}
    do
       showName="${showName} ${serverName} |"
    done
    showName="${showName} all"
    echo "Usage: ./server.sh (${showName})"
}

#判断输入参数
if [ "$1" ]; then
	#echo "test if $1"
	runFlag=""
	index=0 
	for serverName in ${serverNames[@]}
	do
	    #echo "serverName:"$serverName
	    if [ $serverName = $1 ]
	    then
	       runFlag="run"
	       #执行重启
	       restart $1 $basePath
	       #break
	       exit 0
	    elif [[ $serverName =~ "${1}" ]]; then 
		matchNames[$index]=$serverName
		let index++
	    fi
	done
	#模糊匹配提示操作
	if [ $index -gt 0 ]
	then
	    if [ $index -eq 1 ]
	    then
		read -p "Are you sure to restart ${matchNames[($[ ${index}-1 ])]} tomcat?/\n((y) keys to execute /Other keys to exit):" enterKey
		if [ "$enterKey" = "y" -o "$enterKey" = "Y" ]
		then
		    restart "${matchNames[($[ ${index}-1 ])]}" $basePath
		
		else
		    echo "Exit execution."
		fi
	    elif [ $index -gt 1 ]
	    then
		echo "Please select the tomcat service you want to restart."
		for i in "${!matchNames[@]}" 
	        do
		    echo "${matchNames[${i}]}   (${i})-key"
	        done
		echo "Please press another key to exit"
		read -p "please enter:" selectKey
		for i in "${!matchNames[@]}"  
		do  
		    #if grep '^[[:digit:]]*$' <<< "$selectKey";
		    if [ "${selectKey}" -ge 0 ] 2>/dev/null;
		    then
			    if [ "$selectKey" -eq "$i" ]
			    then
				restart "${matchNames[${i}]}" $basePath
				break
			    fi
		    else
		       	echo "Exit execution."
		        break 
		    fi

		done
	    fi
	    exit 0;
	fi

	#重启所有
	if [ $1 = "all" ]
	then
	    for serverName in ${serverNames[@]}
	    do
	       runFlag="run"
	       restart $serverName $basePath
	    done
	fi
	if [ -z "$runFlag" ]; then
	    showWarn
	fi
#	return 0;
else
	showWarn
#    return 1;
fi


